﻿using Core;
using Core.Domain.Stores;
using Services.Stores;
using System;
using System.Linq;

namespace Net.Web.Framework
{
    public partial class WebStoreContext : IStoreContext
    {
        #region Filed
        private readonly IStoreService _storeService;
        private readonly IWebHelper _webHelper;
        private Store _cachedStore;
        #endregion

        #region 构造

        public WebStoreContext(IStoreService storeService, IWebHelper webHelper)
        {
            this._storeService = storeService;
            this._webHelper = webHelper;
        }
        #endregion

        #region Method
        public virtual Store CurrentStore
        {
            get
            {
                if (_cachedStore != null)
                    return _cachedStore;

                var host = _webHelper.ServerVariables("HTTP_HOST");
                var allStores = _storeService.GetAllStores();
                var store = allStores.FirstOrDefault(s => s.ContainsHostValue(host));

                if (store == null)
                {
                    store = allStores.FirstOrDefault();
                }

                _cachedStore = store;
                return _cachedStore;
            }
        }
        #endregion
    }
}
